package com.hotchpotch.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.cretin.www.cretinautoupdatelibrary.utils.CretinAutoUpdateUtils;
import com.hotchpotch.R;
import com.hotchpotch.adapter.MainAdapter;
import com.hotchpotch.base.BaseActivity;
import com.hotchpotch.bean.KillServiceLogBean;
import com.hotchpotch.inter.OnRecyclerViewItemClickListener;
import com.hotchpotch.inter.PermissionListener;
import com.hotchpotch.services.NoKilledService;
import com.hotchpotch.util.InstallUtils;
import com.hotchpotch.util.Logg;
import com.hotchpotch.util.ToastUtil;
import com.hotchpotch.widget.SpaceItemDecoration;
import com.raizlabs.android.dbflow.sql.language.SQLite;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindAnim;
import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    @BindView(R.id.appbar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.tool_bar)
    Toolbar toolbar;
    @BindView(R.id.swipe)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    private MainAdapter adapter;
    private List<String> list = new ArrayList<>();
    @BindView(R.id.floating_btn)
    FloatingActionButton fab;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        setSupportActionBar(toolbar);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.color23c751, R.color.colorPrimary);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new SpaceItemDecoration(0, 0, 0, 10));
        recyclerView.setItemAnimator(new DefaultItemAnimator());//动画添加
        adapter = new MainAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initEvents() {
        //appBarLayout的偏移监听，控制fab的显示或隐藏
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//                Logg.e(TAG, "verticalOffset = " + verticalOffset);
                if (verticalOffset == 0) {
                    fab.setVisibility(View.VISIBLE);
                } else {
                    fab.setVisibility(View.GONE);
                }
            }
        });
        //下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 2000);
            }
        });
        //点击监听
        adapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view) {
                int postion = recyclerView.getChildAdapterPosition(view);
                goPage(view, postion);
                ToastUtil.showToast("点击位置：" + postion);
            }

            @Override
            public void onItemLongClick(View view) {

            }
        });
    }

    private int count = 1;

    @OnClick(R.id.floating_btn)
    void click() {
        ToastUtil.showToast("点了" + count + "次");
        count++;
    }

    @Override
    protected void initData() {
        applyPermiss(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECEIVE_BOOT_COMPLETED, Manifest.permission.READ_PHONE_STATE);
        initItems();
        //apk更新
//        CretinAutoUpdateUtils.getInstance(MainActivity.this).check();
        //开起后台服务
        Intent service = new Intent(MainActivity.this, NoKilledService.class);
        startService(service);
        Logg.e(TAG, "开启服务");
        List<KillServiceLogBean> list1 = SQLite.select().from(KillServiceLogBean.class).queryList();
        Logg.e(TAG, "服务记录 = " + list1);
    }

    private void initItems() {
        list.add("城市列表转换并分类");
        list.add("城市列表转换(只要城市)做字母排序");
        list.add("这个没有内容");
        list.add("加密/解密");
        list.add("RecyclerView下拉刷新/上拉加载更多");
        list.add("bottomnavigationbar");
        list.add("TabLayout导航栏");
        list.add("抽奖转盘");
        list.add("retrofit 2.0");
        list.add("更新APP");
        list.add("自带的时间选择器");
        list.add("DBFlow数据库");
        list.add("后台服务数据显示");
        list.add("扫描二维码");
        for (int i = 0; i < 10; i++) {
            list.add("测试数据");
        }
        adapter.setList(list);
        adapter.notifyDataSetChanged();
    }

    /**
     * 点击跳转
     *
     * @param view
     * @param postion
     */
    private void goPage(View view, int postion) {
        switch (postion) {
            case 0:
                goToPage(MainActivity.this, OneActivity.class);
                break;
            case 1:
                goToPage(MainActivity.this, TwoActivity.class);
                break;
            case 2:
                break;
            case 3://加密/解密
                goToPage(MainActivity.this, EncryptAndDecryptActivity.class);
                break;
            case 4:
                goToPage(MainActivity.this, RecyclerViewRefreshActivity.class);
                break;
            case 5:
                goToPage(MainActivity.this, BottomNavigationbarActivity.class);
                break;
            case 6://TabLayout导航栏
                goToPage(MainActivity.this, TabLayoutAct.class);
                break;
            case 7://旋转图片
                goToPage(MainActivity.this, RotateImageActivity.class);
                break;
            case 8://retrofit 2.0
                goToPage(MainActivity.this, RetrofitActivity.class);
                break;
            case 9://更新apk
                goToPage(MainActivity.this, UpdateApkActivity.class);
                break;
            case 10://自带时间选择器
                goToPage(MainActivity.this, PickerAct.class);
                break;
            case 11://DBFlow数据库
                goToPage(MainActivity.this, DBFlowAct.class);
                break;
            case 12://后台服务数据展示
                goToPage(MainActivity.this, KillServiceAct.class);
                break;
            case 13://扫描二维码
                goToPage(MainActivity.this, TestScanActivity.class);
                break;
            default:
                ToastUtil.showSnakeBar(view, "点击位置" + postion, "关闭", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtil.showToast("关闭了底部弹窗");
                    }
                });
                break;
        }
    }

    /**
     * 更新Apk
     */
    //最新APK的下载地址
    public static final String APK_URL = "http://mobile.ac.qq.com/qqcomic_android.apk";
    //下载后的APK的命名
    public static final String APK_NAME = "update";

    private void checkUpdate() {
        new InstallUtils(MainActivity.this, APK_URL, APK_NAME, new InstallUtils.DownloadCallBack() {
            @Override
            public void onStart() {
                Logg.i(TAG, "InstallUtils---onStart");
//            tv_progress.setText("0%");//进度
            }

            @Override
            public void onComplete(String path) {
                Logg.i(TAG, "InstallUtils---onComplete:" + path);

                /**
                 * 安装APK工具类
                 * @param context       上下文
                 * @param filePath      文件路径
                 * @param authorities   ---------Manifest中配置provider的authorities字段---------
                 * @param callBack      安装界面成功调起的回调
                 */
                InstallUtils.installAPK(MainActivity.this, path, getPackageName() + ".fileProvider", new InstallUtils.InstallCallBack() {
                    @Override
                    public void onSuccess() {
                        showToast("正在安装");
                    }

                    @Override
                    public void onFail(Exception e) {
                        showToast("安装失败");
                    }
                });
//            tv_progress.setText("100%");//进度
            }

            @Override
            public void onLoading(long total, long current) {
                Logg.i(TAG, "InstallUtils----onLoading:-----total:" + total + ",current:" + current);
//            tv_progress.setText((int) (current * 100 / total) + "%");//进度
            }

            @Override
            public void onFail(Exception e) {
                Logg.i(TAG, "InstallUtils---onFail:" + e.getMessage());
            }

        }).downloadAPK();
    }

    private void applyPermiss(String... strings) {
        requestRunPermission(strings, new PermissionListener() {
            @Override
            public void onGranted() {

            }

            @Override
            public void onDenied(List<String> deniedPermissions) {
                for (String deniedPermission : deniedPermissions) {
                    ToastUtil.showToast(deniedPermission + "权限被拒");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CretinAutoUpdateUtils.getInstance(this).destroy();//销毁
    }
}
